package com.wenyp;

import com.itextpdf.io.font.FontProgram;
import com.itextpdf.io.font.FontProgramFactory;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.*;
import com.itextpdf.layout.element.Image;
import com.itextpdf.layout.element.List;
import com.itextpdf.layout.properties.UnitValue;
import org.junit.Before;
import org.junit.Test;

import java.awt.*;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Paths;
import java.util.StringTokenizer;

/**
 * 高级对象块的应用
 * Paragraph List Image TableCell
 */
public class HelloIText {

    public static String rootPath = "";

    @Before
    public void init(){
        rootPath = Paths.get("").toAbsolutePath().toString() + "/src/main/resources/";
        System.out.println("项目根路径: " + rootPath);
    }

    @Test
    public void testRootPath(){
        rootPath = HelloIText.class.getClassLoader().getResource("").getPath();
        System.out.println("类加载方式获取项目根路径: " + rootPath);

        rootPath = Paths.get("").toAbsolutePath().toString();
        System.out.println("NIO获取项目根路径: " + rootPath);

        rootPath = System.getProperty("user.dir");
        System.out.println("环境变量获取项目根路径: " + rootPath);
    }

    @Test
    public void hello() throws FileNotFoundException {
        String DEST = rootPath  + "/pdfFiles/hello.pdf";
        try(PdfDocument pdfDocument = new PdfDocument(new PdfWriter(DEST));){
            try(Document document = new Document(pdfDocument);){
                String line = "Hello! Welcome to iTextPdf";
                document.add(new Paragraph(line));

                System.out.println("Awesome PDF just got created.");
            }
        }
    }

    @Test
    public void test_Font() throws IOException {
        String DEST = rootPath  + "/pdfFiles/test_Font.pdf";
        try(PdfDocument pdfDocument = new PdfDocument(new PdfWriter(DEST));
            Document document = new Document(pdfDocument);){
            // Create a PdfFont
            // 获取系统中可用的 Arial 字体程序
            FontProgram fontProgram = FontProgramFactory.createFont("Helvetica");
            PdfFont font = PdfFontFactory.createFont(fontProgram);
            // Add a Paragraph
            document.add(new Paragraph("iText is:").setFont(font));
            // Create a List
            List list = new List()
                    .setSymbolIndent(12)
                    .setListSymbol("\u2022")
                    .setFont(font);
            // Add ListItem objects
            list.add(new ListItem("Never gonna give you up"))
                    .add(new ListItem("Never gonna let you down"))
                    .add(new ListItem("Never gonna run around and desert you"))
                    .add(new ListItem("Never gonna make you cry"))
                    .add(new ListItem("Never gonna say goodbye"))
                    .add(new ListItem("Never gonna tell a lie and hurt you"));
            // Add the list
            document.add(list);
        }
    }

    @Test
    public void test_image() throws FileNotFoundException, MalformedURLException {
        String DEST = rootPath  + "/pdfFiles/test_image.pdf";
        String FOX = rootPath  + "/img/fox.jpg";
        String DOG = rootPath  + "/img/dog.jpg";
        try(PdfDocument pdfDocument = new PdfDocument(new PdfWriter(DEST));){
            try(Document document = new Document(pdfDocument);){
                Image fox = new Image(ImageDataFactory.create(FOX));
                Image dog = new Image(ImageDataFactory.create(DOG));
                Paragraph p = new Paragraph("The quick brown ")
                        .add(fox)
                        .add(" jumps over the lazy ")
                        .add(dog);
                document.add(p);
            }
        }
    }

    @Test
    public void test_font_list(){
        // 获取系统中可用的字体列表
        String[] fontNames = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();

        // 打印可用的字体列表
        System.out.println("系统中可用的字体列表：");
        for (String fontName : fontNames) {
            System.out.println(fontName);
        }
    }

    @Test
    public void test_data() throws IOException {
        String DEST = rootPath  + "/pdfFiles/test_data.pdf";
        String DATA = rootPath  + "/data/united_states.csv";
        try(PdfDocument pdfDocument = new PdfDocument(new PdfWriter(DEST));){
            try(Document document = new Document(pdfDocument, PageSize.A4.rotate());){ //默认尺寸为A4
                document.setMargins(20, 20, 20, 20);
                PdfFont font = PdfFontFactory.createFont("Helvetica");
                PdfFont bold = PdfFontFactory.createFont("Helvetica-Bold");
                Table table = new Table(new float[]{4, 1, 3, 4, 3, 3, 3, 3, 1}); //列宽度定义
                table.setWidth(UnitValue.createPercentValue(100)); //页面可用宽度
                try(BufferedReader br = new BufferedReader(new FileReader(DATA))){
                    String line = br.readLine();
                    process(table, line, bold, true);
                    while ((line = br.readLine()) != null) {
                        process(table, line, font, false);
                    }
                }

                document.add(table);
            }
        }
    }

    public void process(Table table, String line, PdfFont font, boolean isHeader) {
        StringTokenizer tokenizer = new StringTokenizer(line, ";");
        while (tokenizer.hasMoreTokens()) {
            if (isHeader) {
                table.addHeaderCell(
                        new Cell().add(
                                new Paragraph(tokenizer.nextToken()).setFont(font)));
            } else {
                table.addCell(
                        new Cell().add(
                                new Paragraph(tokenizer.nextToken()).setFont(font)));
            }
        }
    }



}
